package com.wjr.braveheart.http;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @Description: 处理网络请求参数的工具类
 * //TODO: 存疑 addFormDataPart方法中 { key + i } 参数不理解其含义
 * @Author: 长安三日
 * @Email: 邮箱
 * @CreateDate: 2020/6/6 11:20
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 * PS: You can change the world with code! Don't give up!
 */
public class ParamsUtils {

    /**
     * 拼接 url 和 params
     *
     * @param url
     * @param params
     * @return
     */
    public static String appendParams(String url, Map<String, Object> params) {
        if (params != null && params.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer(url);
            if (!url.contains("?")) {
                // 不包含 ? 直接添加一个
                stringBuffer.append("?");
            }

            if (!url.endsWith("?")) {
                // 如果不是以 ? 结尾
                stringBuffer.append("&");
            }

            Iterator iterator = params.entrySet().iterator();

            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                stringBuffer.append(entry.getKey() + "=" + entry.getValue() + "&");
            }

            stringBuffer.deleteCharAt(stringBuffer.length() - 1);

            return stringBuffer.toString();
        } else {
            return url;
        }
    }

    /**
     * 组装 requestBody
     *
     * @param params 参数
     * @return MultipartBody
     */
    public static RequestBody appendBody(Map<String, Object> params) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        addParams(builder, params);
        return builder.build();
    }

    /**
     * 添加参数
     *
     * @param builder MultipartBody.Builder
     * @param params  参数
     */
    private static void addParams(MultipartBody.Builder builder, Map<String, Object> params) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value instanceof File) {
                    // 处理文件 --> Object File
                    File file = (File) value;
                    builder.addFormDataPart(key, file.getName(), RequestBody.Companion
                            .create(file, MediaType.Companion.parse(guessMimeType(file.getAbsolutePath()))));
                } else if (value instanceof List) {
                    // 代表提交的是 List集合
                    try {
                        List<File> listFiles = (List<File>) value;
                        for (int i = 0; i < listFiles.size(); i++) {
                            // 获取文件
                            File file = listFiles.get(i);
                            builder.addFormDataPart(key + i, file.getName(), RequestBody.Companion
                                    .create(file, MediaType.Companion.parse(guessMimeType(file.getAbsolutePath()))));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    builder.addFormDataPart(key, value + "");
                }
            }
        }
    }

    /**
     * 猜测文件类型
     *
     * @param path 路径
     * @return String
     */
    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
}
